<template>
  <view>
    <view class="all">
      <view class="adress">
        <view v-if="defaultAddress">
          <view class="adress-header">
            收货地址
            <img @click="goToAddressPage" src="../../static/imgs/进入.png" style="width:20px;height:20px;margin-left:20px">
          </view>
          <view class="adress-body">
            {{defaultAddress.city}}{{defaultAddress.department}}{{defaultAddress.houseNumber}}
          </view>
          <view class="adress-name">{{defaultAddress.name}} &nbsp;{{defaultAddress.phone}}</view>
        </view>
        <view v-else>
          <view class="adress-header">请选择收货地址</view>
          <view class="adress-body" @click="goToAddressPage">
            点击选择收货地址
          </view>
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="shop">
      <view class="title">沃尔玛</view>
      <view class="shop-list" v-for="(item, index) in shoplist" :key="index">
        <image :src="item.img" />
        <view class="product-info">
          <view class="name">{{ item.name }}</view>
          <view class="price">
            <view class="new">￥{{ item.price }} x {{item.quantity}}</view>
            <view class="zong">￥{{ (item.price * item.quantity).toFixed(2) }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部金额显示 -->
    <view class="foot fixed-bottom">
      <view class="left">实付金额：￥{{ numtotal }}</view>
      <view class="right" @click="submit()">提交订单</view>
    </view>
  </view>
</template>

<script>
import config from '../config.js';
export default {
  data() {
    return {
      adresslist: [],
      defaultAddress: null,
      shoplist: [],
      isFirstLoad: true
    };
  },
  onLoad(options) {
    this.parseOptionsData(options);
  },
  onShow() {
    if (this.isFirstLoad) {
      this.loadDefaultAddress();
      this.isFirstLoad = false;
    }
  },
  methods: {
    parseOptionsData(options) {
      // 解析地址数据
      if (options.selectedAddress) {
        try {
          this.defaultAddress = JSON.parse(decodeURIComponent(options.selectedAddress));
          console.log('解析后的地址:', this.defaultAddress);
        } catch (error) {
          console.error('解析地址失败:', error);
          uni.showToast({
            title: '地址数据加载失败',
            icon: 'none'
          });
        }
      }

      // 解析商品数据
      if (options.selectedItems) {
        try {
          this.shoplist = JSON.parse(decodeURIComponent(options.selectedItems));
          console.log('解析后的商品列表:', this.shoplist);

          // 确保每个商品都有必要的字段
          this.shoplist = this.shoplist.map(item => ({
           ...item,
            price: Number(item.price) || 0,
            quantity: Number(item.quantity) || 1
          }));
        } catch (error) {
          console.error('解析商品失败:', error);
          uni.showToast({
            title: '商品数据加载失败',
            icon: 'none'
          });
        }
      }
    },
    loadDefaultAddress() {
      uni.request({
        url: config.api_host + '/address',
        success: (res) => {
          if (res.data && res.data.length > 0) {
            this.defaultAddress = res.data[0];
            this.adresslist = res.data;
          } else {
            console.warn('没有获取到地址数据');
          }
        },
        fail: (err) => {
          console.error('加载地址失败:', err);
          uni.showToast({
            title: '加载地址失败，请稍后重试',
            icon: 'none'
          });
        }
      });
    },
    goToAddressPage() {
      uni.navigateTo({
        url: `/pages/dingdan/adress?addressList=${encodeURIComponent(JSON.stringify(this.adresslist))}`
      });
    },
    submit() {
      if (!this.defaultAddress) {
        uni.showToast({
          title: '请先选择收货地址',
          icon: 'none'
        });
        return;
      }

      if (this.shoplist.length === 0) {
        uni.showToast({
          title: '没有选择商品',
          icon: 'none'
        });
        return;
      }

      uni.showModal({
        title: '确认订单',
        content: `总金额: ￥${this.numtotal}\n请尽快完成支付`,
        success: (res) => {
          if (res.confirm) {
            const orderData = {
              address: this.defaultAddress,
              products: this.shoplist,
              totalPrice: this.numtotal,
              createTime: new Date().toISOString()
            };
            uni.navigateTo({
              url: `/pages/dingdan/pay?orderData=${encodeURIComponent(JSON.stringify(orderData))}&totalPrice=${this.numtotal}`
            });
          }
        }
      });
    }
  },
  computed: {
    numtotal() {
      const total = this.shoplist.reduce((sum, item) => {
        return sum + (Number(item.price) || 0) * (Number(item.quantity) || 1);
      }, 0);
      console.log('计算总金额:', total); // 调试
      return total.toFixed(2);
    }
  }
};
</script>

<style>
/* 原有样式保持不变 */
.all {
  width: 100%;
  height: 150px;
  background-image: linear-gradient(to bottom, #0091ff, #fff);
  padding-top: 100px;
}
.all .adress {
  width: 93%;
  height: 100px;
  margin: 0px auto;
  background-color: #fff;
  border-radius: 5px;
  padding: 10px; /* 增加内边距，让内容更舒展 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}
.adress-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.adress-body {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}
.adress-name {
  font-size: 14px;
  color: #666;
}
/* 优化后的样式 */
.shop {
  padding: 10px;
  background-color: #f9f9f9;
}
.shop .title {
  font-size: 20px;
  margin-bottom: 10px;
  text-align: center;
}
.shop-list {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
}
.shop-list image {
  width: 80px;
  height: 80px;
  margin-right: 10px;
}
.product-info {
  flex: 1;
}
.name {
  font-size: 16px;
  margin-bottom: 5px;
}
.price {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.new {
  color: #FF5500;
}
.zong {
  font-weight: bold;
}
.foot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 100; /* 确保在其他元素之上 */
}
.foot .left {
  line-height: 60px;
  font-size: 18px;
  font-weight: 600;
  margin: 0 30px;
  color: #333; /* 确保文字颜色可见 */
}
.foot .right {
  background-color: #0091ff;
  color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  text-align: center;
}
</style>